<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<head>
    <th:block th:include="common/common_head :: commonHeader('询价单录入')"/>
    <link th:href="@{/static/css/plugins/cropper/cropper.min.css}" rel="stylesheet">
</head>

<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <form class="form-horizontal" method="post" id="inquiryHeaderForm">
        <div class="row">
            <div class="form-group">
                <div class="col-sm-8" style="margin-left: 16px">
                    <input class="btn btn-primary" type="button" onclick="save()" value="保存">
                    <button class="btn btn-primary" type="button" onclick="Dialog.closeFrame(window.name)">取 消</button>
                </div>
            </div>

            <!-- 显示 隐藏测试 -->
            <ul id="myTab" class="nav nav-tabs">
                <li class="active">
                    <a href="#basicinformation" linkTab="basicinformation" isActive="true" data-toggle="tab"> 基础信息</a>
                </li>
                <li>
                    <a href="#materialformation" linkTab="materialformation" data-toggle="tab"> 物料信息</a>
                </li>
                <li>
                    <a href="#vendorformation" linkTab="vendorformation" data-toggle="tab"> 供应商基本信息</a>
                </li>
            </ul>

            <!-- 基本信息 -->
            <div id="basicinformation">
                <div class="ibox float-e-margins">
                    <div class="ibox-content">
                        <div class="form-group">
                            <label class="col-xs-1 control-label"><span class="required-sign">*</span>汇总号：</label>
                            <div class="col-xs-3">
                                <input name="inquiryTotalCode" type="text" placeholder="汇总号" class="form-control"
                                       readonly="readonly">
                            </div>
                            <label class="col-xs-1 control-label">公司代码：</label>
                            <div class="col-xs-3">
                                <select class="form-control" id="companyCode" name="companyCode" sysDict="GC"
                                        emptyFirst="true" th:data-val="${companyCode}"></select>
                            </div>
                            <div class="form-group">
                                <label class="col-xs-1 control-label">采购组织</label>
                                <div class="col-xs-3">
                                    <select class="form-control required" title="请输入采购组织" id="purchaseOrg"
                                            name="purchaseOrg" sysDict="CGZZ" emptyFirst="true"
                                            th:data-val="${purchaseOrg}"></select>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-1 control-label"><span class="required-sign">*</span>采购组：</label>
                            <div class="col-sm-3">
                                <select class="form-control required" id="purchaseGrp" name="purchaseGrp"
                                        title="请输入采购组织" sysDict="CGZ" emptyFirst="true"
                                        th:data-val="${purchaseGrp}"></select>
                            </div>
                            <label class="col-sm-1 control-label">语言编码：</label>
                            <div class="col-sm-3">
                                <input class="form-control required" name="language" id='language' title="请输入语言编码"
                                       type="text" placeholder="地址" th:value="ZH"/>
                            </div>
                            <label class="col-sm-1 control-label">货币：</label>
                            <div class="col-sm-3">
                                <select class="form-control required" title="请输入货币" id="currency" name="currency"
                                        sysDict="BZ" th:data-val="${currency}"></select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-1 control-label">询价开始日期：</label>
                            <div class="col-sm-3">
                                <input class="form-control required" title="询价开始日期" name="beginDate" id="beginDate"
                                       type="text" placeholder="询价开始日期" th:value="${beginDate}" readonly="readonly">
                            </div>
                            <label class="col-sm-1 control-label">报价截止日期：</label>
                            <div class="col-sm-3">
                                <input class="form-control required" title="报价截止日期" name="endDate" id="endDate"
                                       type="text" placeholder="报价截止日期" autocomplete="off">
                            </div>
                            <label class="col-sm-1 control-label">抬头备注</label>
                            <div class="col-sm-3">
                                <input name="remark" type="text" placeholder="抬头备注" class="form-control">
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 物料信息 -->
            <div id="materialformation" style="display:none;">
                <div class="ibox float-e-margins">
                    <div class="table-responsive">
                        <table class="table table-bordered text-nowrap" id="para_table">
                            <thead>
                            <tr>
                                <th>物料编码</th>
                                <th>物料描述</th>
                                <th>采购申请编码</th>
                                <th>数量</th>
                                <th>单位</th>
                                <th>交货日期</th>
                                <th>工厂</th>
                                <th>库存地点</th>
                                <th>物料组</th>
                                <th>参考行项目</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr th:each="ProPurchRequestItemEntity : ${itemlist}">
                                <td style="display:none"><input name="inquiryItemId" type="hidden"
                                                                th:value="${ProPurchRequestItemEntity.pkId}"/></td>
                                <td width='110px'><input style='width:95%' name='materialCode'
                                                         th:value="${ProPurchRequestItemEntity.materialCode}"
                                                         readonly="ture"/></td>
                                <td width='110px'><input style='width:95%' name='materialDesc'
                                                         th:value="${ProPurchRequestItemEntity.materialDesc}"
                                                         readonly="ture"/></td>
                                <td width='110px'><input style='width:95%' type='text' name='requestCode'
                                                         th:value="${ProPurchRequestItemEntity.purchRequestCode}"
                                                         readonly="ture"/></td>
                                <td width='110px'><input style='width:95%' type='text' name='purchaseCnt'
                                                         th:value="${ProPurchRequestItemEntity.applyQty}"
                                                         readonly="ture"/></td>
                                <td width='110px'><input style='width:95%' type='text' name='poUnit'
                                                         th:value="${ProPurchRequestItemEntity.measureUnit}"
                                                         readonly="ture"/></td>
                                <td width='110px'><input style='width:95%' type='text' name='deliveryDate'
                                                         th:value="${#dates.format(ProPurchRequestItemEntity.deliveryDate,'yyyy-MM-dd')}"
                                                         readonly="ture"/></td>
                                <td width='110px'><input style='width:95%' type='text' name='werks'
                                                         th:value="${ProPurchRequestItemEntity.factory}"
                                                         readonly="ture"/></td>
                                <td width='110px'><input style='width:95%' type='text' name='storageLocation'
                                                         th:value="${ProPurchRequestItemEntity.storageLocation}"
                                                         readonly="ture"/></td>
                                <td width='110px'><input style='width:95%' type='text' name='materialGroup'
                                                         th:value="${ProPurchRequestItemEntity.materialGroup}"
                                                         readonly="ture"/></td>
                                <td width='110px'><input style='width:95%' type='text' name='purchRequestItemCode'
                                                         th:value="${ProPurchRequestItemEntity.purchRequestItemCode}"
                                                         readonly="ture"/></td>
                                <td width='110px'></td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <!-- 供应商信息 -->
            <div id="vendorformation" style="display:none;">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <!-- <button type="button" class="btn btn-xs btn-link" onclick='addtr("vendorformation")'>添加</button> -->
                        <button type="button" class="btn  btn-rounded btn-sm" onclick='addtr("vendorformation")'><i
                                class="fa fa-plus"></i>&nbsp;添加
                        </button>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-bordered text-nowrap" id="vendor_table">
                            <thead>
                            <tr>
                                <th>供应商编码</th>
                                <th>供应商名称</th>
                                <th>付款条件</th>
                                <th>国际贸易条款</th>
                                <th>税代码</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<!-- Modal Vendor -->
<div class="modal fade" id="myModalVendor" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document" style="width:70%">
        <div class="modal-content" style="height:700px">
            <form id="vendorForm" th:action="@{/vendor/findSimplePage}" class="form-inline">
                <div class="modal-header" style="height:10%">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">供应商选择</h4>
                </div>
                <div class="modal-body">
                    <div style="height: 30px">
                        <ul>
                            <li class="col-sm-3" style="width: 33%">
                                <label>供应商编码：</label>
                                <input name=sapCode type="text" id="sapCode" class="form-control" placeholder="供应商编码">
                            </li>
                            <li class="col-sm-3" style="width: 33%">
                                <label>供应商名称：</label>
                                <input name="vendorName" type="text" id="vendorName" class="form-control"
                                       placeholder="供应商名称">
                            </li>
                            <li class="col-sm-3" style="width: 33%">
                                <button id="vendorSearchBtn" type="button" class="btn btn-primary btn-rounded btn-sm"><i
                                        class="fa fa-search"></i>&nbsp;搜索
                                </button>
                                <button class="btn btn-warning btn-rounded btn-sm" type="reset"><i
                                        class="fa fa-eraser"></i>&nbsp;重置
                                </button>
                            </li>
                        </ul>
                    </div>
                    <table id="vendor" class="table table-bordered"></table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick='check_form("vendor")'>确定</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!--引入公共js-->
<div th:include="common/onload_js :: onloadJS"></div>
<!-- Chosen -->
<script th:src="@{/static/js/plugins/chosen/chosen.jquery.js}"></script>

<!-- 文件上传的function -->
<script type="text/javascript">
    var filenames = [];
    $(function () {
        initTabBar("myTab");
    });
</script>
<script type="text/javascript">

    $(function () {
        // 初始化时间插件
        //laydate.render({elem: '#beginDate'});
        laydate.render({elem: '#endDate'});
        //laydate.render({elem: '#deliveryDate'});
        //初始化所有字典数据
        initDictDataSel();
    });

    var materialCode = "";
    var materialDesc = "";
    var werks = "";
    var materialGroup = "";
    var id;

    function check_form(obj) {
        //使用getSelections即可获得，row是json格式的数据
        var rows = $("#" + obj).bootstrapTable('getSelections');
        //判断是否选中行
        if (!rows || rows.length == 0) {
            Dialog.alert("请先选中一行！")
            return;
        }
        if (rows[0].freeze == 1) {
            Dialog.errorMsg("该供应商已被冻结，不可选择！");
            return false;
        }
        showTableData(rows[0], obj);
    }

    function showTableData(json, obj) {
        if ("vendor" == obj) {
            //$("#vendor_table").bootstrapTable('removeAll');
            $("#vendor_table td input[id='sapCode" + id + "']").val(json.sapCode);
            $("#vendor_table td input[id='" + "vendorName" + id + "']").val(json.vendorName);
            $("#vendor_table td select[id='payCondition" + id + "']").val(json.payCondition);
            $("#vendor_table td select[id='i18nTradeTerms" + id + "']").val(json.i18nTradeTerms);
            //新增税代码 yanfei
            $("#vendor_table td select[id='taxCode" + id + "']").val(json.taxCode);
            $('#myModalVendor').modal('hide');
        }
        if ("materialFactory" == obj) {
            //$("#para_table").bootstrapTable('removeAll');
            $("#para_table td input[id='materialCode" + id + "']").val(json.materialFactoryEntity.materialCode);
            $("#para_table td input[id='materialDesc" + id + "']").val(json.materialEntity.materialDesc);
            $("#para_table td select[id='werks" + id + "']").val(json.materialFactoryEntity.werks);
            $("#para_table td input[id='materialGroup" + id + "']").val(json.materialFactoryEntity.werks);
            $('#myModal').modal('hide');
        }
    }

    Searcher.createBS('#materialFactory',
        [
            {radio: true},
            {title: "物料号", field: "materialFactoryEntity.materialCode"},
            {title: "物料描述", field: "materialEntity.materialDesc"},
            {title: "工厂", field: "materialFactoryEntity.werks"},
            {title: "物料组", field: "materialEntity.materialGroup"}
        ], {pageList: [10], pageSize: 10, showColumns: false, showRefresh: false}
    );
    Searcher.createBS('#vendor',
        [
            {radio: true},
            {title: "供应商编码", field: "sapCode"},
            {title: "供应商名称", field: "vendorName"},
            {title: "公司代码", field: "compCode"},
            {title: "付款条件", field: "payCondition"},
            {title: "税代码", field: "taxCode"}
        ], {pageList: [10], pageSize: 10, showColumns: false, showRefresh: false}
    );

    //新增行
    var index = 0;
    var index1 = 0;

    function addtr(obj) {
        if ("vendorformation" == obj) {
            var mydate = new Date();
            var uuid = "rdn" + mydate.getDay() + mydate.getHours() + mydate.getMinutes() + mydate.getSeconds() + mydate.getMilliseconds();//根据时间来自动生成uuid，保证生成的id是唯一的
            var trCode = "<tr>";

            trCode += "<td><input id='sapCode" + index1 + "' name='sapCode' readonly='readonly' data-ids='" + index1 + "' data-toggle='modal' data-target='#myModalVendor' /></td>";
            trCode += "<td><input id='vendorName" + index1 + "' style='width:95%' name='vendorName' readonly='readonly' /></td>";
            trCode += "<td><select id='payCondition" + index1 + "' style='width:95%' name='payCondition' class='form-control required' title='请输入付款条款' disabled='true' dictType='FKTJ' emptyFirst='true'></select></td>";
            trCode += "<td><select id='i18nTradeTerms" + index1 + "' style='width:95%' name='i18nTradeTerms' class='form-control required' title='请输入国际贸易条款' disabled='true' dictType='GJMYTK' emptyFirst='true'/></td>";
            //增加税代码
            trCode += "<td><select id='taxCode" + index1 + "' style='width:95%' name='taxCode' class='form-control required' title='请输入税代码' disabled='true' dictType='SDM' emptyFirst='true'/></td>";
            trCode += "<td  align='center' onclick='deletetr(this)'><button type='button' class='btn btn-xs btn-link'>" + "删除" + "</button></td>";
            trCode += "</tr>";
            $("#vendor_table tbody").append(trCode);
            index1 = index1 + 1;
            $('#myModalVendor').on('show.bs.modal', function (event) {
                var b = $(event.relatedTarget) // relatedTarget 事件属性返回与事件的目标节点相关的节点。
                var ids = b.context.dataset.ids;
                id = ids;
            })
        }
        fillDictDataSel();//自动往select框里面填充字典数据
    }

    function deletetr(tdobject) {
        $(tdobject).parents("tr").remove();
    }

    function save() {
        //回填下拉数据
        //required:true
        if ($("#inquiryHeaderForm").valid()) {
            //验证基础信息中必填项是否填写（$("#inquiryHeaderForm").valid()切换选项卡会失效）
            if ($("#companyCode").val() == null || $("#companyCode").val() == '') {
                Dialog.errorMsg("填写基础信息页 公司代码！");
                return;
            }
            if ($("#purchaseOrg").val() == null || $("#purchaseOrg").val() == '') {
                Dialog.errorMsg("填写基础信息页 采购组织！");
                return;
            }
            if ($("#purchaseGrp").val() == null || $("#purchaseGrp").val() == '') {
                Dialog.errorMsg("填写基础信息页 采购组！");
                return;
            }
            if ($("#language").val() == null || $("#language").val() == '') {
                Dialog.errorMsg("填写基础信息页 语言编码！");
                return;
            }
            if ($("#currency").val() == null || $("#currency").val() == '') {
                Dialog.errorMsg("填写基础信息页 货币！");
                return;
            }
            if ($("#endDate").val() == null || $("#endDate").val() == '') {
                Dialog.errorMsg("填写基础信息页 报价截止日期！");
                return;
            }
            var data = {
                "inquiryHeaderEntity": {},
                "inquiryItemEntitylist": [],
                "vendorInfolist": [],
                "filenames": filenames,
                "flag": ""
            };//先定义数据结构，head是一个对象，item是一个数组
            //得到head div 下的 input select
            var dataTitle = $("#basicinformation").find("input, select");
            dataTitle.each(function (index, item) {//循环遍历，把head的内容塞进head对象
                //这里进行数据校验
                if ($(item).val() != "undefined" && $(item).val() != null && $(item).val() != "") {
                    data.inquiryHeaderEntity[$(item).attr("name")] = $(item).val();
                }
            });
            if (JSON.stringify(data.inquiryHeaderEntity) == "{}") {
                delete data.inquiryHeaderEntity;
            }
            //得到物料行项目数据
            var trs = $("#para_table").find("tr");
            trs.each(function (index, tr) {//循环遍历，把item的内容塞进一个item对象，然后加到数组里
                var itemEntity = {};
                var its = $(tr).find("input, select");
                its.each(function (idx, it) {//循环遍历，把item的内容塞进一个item对象，然后加到数组里
                    itemEntity[$(it).attr("name")] = $(it).val();
                });
                if (JSON.stringify(itemEntity) != "{}") {
                    data.inquiryItemEntitylist.push(itemEntity);
                }
            });
            //得到供应商行项目数据
            var trs = $("#vendor_table").find("tr");
            trs.each(function (index, tr) {//循环遍历，把item的内容塞进一个item对象，然后加到数组里
                var itemEntity = {};
                var its = $(tr).find("input, select");
                its.each(function (idx, it) {//循环遍历，把item的内容塞进一个item对象，然后加到数组里
                    itemEntity[$(it).attr("name")] = $(it).val();
                });
                if (JSON.stringify(itemEntity) != "{}") {
                    data.vendorInfolist.push(itemEntity);
                }
            });
            if (data.vendorInfolist.length == 0) {
                delete data.vendorInfolist;
                var r = confirm("警告 : 请添加供应商信息");
                if (r == true) {
                    document.write("确认");
                }
            } else {
                if (data.inquiryItemEntitylist.length == 0) {
                    delete data.inquiryItemEntitylist;
                    var r = confirm("警告 : 请添物料信息");
                    if (r == true) {
                        document.write("确认");
                    }
                } else {
                    //点击保存后上传
                    $("#input-id").fileinput("upload");
                    layer.load(1, {shade: [0.3, '#393D49']});
                    $.ajax({
                        type: "POST",
                        url: ctxPath + "/inquiryHeader/save",
                        data: JSON.stringify(data),//必须
                        contentType: "application/json;charset=UTF-8",//必须
                        dataType: "json",//必须
                        cache: true,
                        async: false,
                        error: function (request) {
                            layer.closeAll();
                            showTipAlert("Connection error");
                        },
                        success: function (data) {
                            layer.closeAll();
                            Dialog.msg("新增成功!", function () {
                                Dialog.closeFrame(window.name);
                            });
                            //刷新父表格
                            window.parent.itemBS.refresh();
                        }
                    });
                }
            }
        }
    }
</script>

</body>
</html>
